package com.gxzy.util.convert;

import com.gxzy.util.SnowflakeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.AttributeConverter;
import java.util.ArrayList;
import java.util.List;

/**
 * AttributeConverter: 此接口用于转化实体属性的
 * 将实体类中的List与数据库中的String互转
 */

public class ListAndStringConvert implements AttributeConverter<List, String> {
    private static String split = "\\|";
    private static String tag = "|";

    private static Logger log = LoggerFactory.getLogger(ListAndStringConvert.class);

    @Override
    public String convertToDatabaseColumn(List value) {
        return getDatabaseColumn(value);
    }

    @Override
    public List convertToEntityAttribute(String value) {
        try {
            if (StringUtils.isEmpty(value)) {
                return null;
            }

            String[] steps = value.split(split);
            List res = new ArrayList();
            for (String v : steps) {
                // 判断数据是否为雪花算法生成
                if (StringUtils.isNumeric(v) && v.length() == SnowflakeUtils.LEN) {
                    res.add(Long.valueOf(v));
                } else {
                    res.add(v);
                }
            }

            return res;
        } catch (Exception e) {
            log.error("表字段转换到实体属性", e);
        }
        return null;
    }

    public static String getDatabaseColumn(List value) {
        try {
            if (null == value || value.size() == 0) {
                return null;
            }

            return StringUtils.join(value, tag);
        } catch (Exception e) {
            log.error("实体属性转换到表字段", e);
        }
        return null;
    }

    public static String getChildDatabaseColumn(List value, Long id) {
        String databaseColumn = getDatabaseColumn(value);
        if (databaseColumn != null) {
            databaseColumn += tag + id;
        }
        return databaseColumn;
    }
}
